package cn.magicman.demo;

import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

public class CompletableFutureDemo {
    static void task(String name, int ms) throws InterruptedException {
        long start = System.nanoTime();
        Thread.sleep(ms);
        long cost = (System.nanoTime() - start) / 1_000_000;
        System.out.printf("[%s] 完成! 耗时: %dms%n", name, cost);
    }

    public static void main(String[] args) throws Exception {
        // 配置参数
        int tasks = 3, taskTime = 1000, mainWorkTime = 200;
        
        // 同步执行（会阻塞主线程）
        System.out.println("====== 同步执行 ======");
        long syncStart = System.nanoTime();
        for (int i = 0; i < tasks; i++) {
            task("同步任务-" + i, taskTime);
        }
        System.out.printf("同步总耗时: %.2fms%n%n", (System.nanoTime() - syncStart) / 1_000_000.0);

        // 异步执行（并行）
        System.out.println("====== 异步执行 ======");
        ExecutorService pool = Executors.newFixedThreadPool(tasks);
        AtomicInteger completed = new AtomicInteger();
        long asyncStart = System.nanoTime();
        
        // 提交所有异步任务
        for (int i = 0; i < tasks; i++) {
            final int taskId = i;
            CompletableFuture.runAsync(() -> {
                try {
                    task("异步任务-" + taskId, taskTime);
                    if (completed.incrementAndGet() == tasks) {
                        System.out.printf("%n异步总耗时: %.2fms%n", 
                            (System.nanoTime() - asyncStart) / 1_000_000.0);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }, pool);
        }
        
        // 主线程继续工作（非阻塞）
        System.out.println("主线程正在处理其他工作...");
        Thread.sleep(mainWorkTime);
        System.out.println("主线程工作完成");
        
        pool.shutdown();
    }
}